<?php

namespace app\model;

class UsersModel extends BaseModel
{
    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * 隐藏的属性
     *
     * @var array
     */
    protected $hidden = ['password'];
    
    /**
     * 属性类型转换
     *
     * @var array
     */
    protected $casts = [
        'created_at' => 'timestamp',
        'updated_at' => 'timestamp',
        'last_login_time' => 'date:Y-m-d H:i:s',
        'birthday' => 'date:Y-m-d',
        'gender' => 'integer',
        'status' => 'integer',
    ];

    /**
     * 根据登录方式查找用户
     *
     * @param string $identifier 标识符（用户名、手机号、邮箱、openid等）
     * @param string $loginType 登录方式
     * @return UsersModel|null
     */
    public static function findByLoginType($identifier, $loginType)
    {
        switch ($loginType) {
            case 'username':
                return self::where('username', $identifier)
        
                    ->orWhere('email', $identifier)
                    ->first();
            case 'wechat':
                return self::where('wechat_openid', $identifier)->first();
            case 'wechat_mp':
                return self::where('wechat_mp_openid', $identifier)->first();
            default:
                return null;
        }
    }

    /**
     * 创建或更新微信用户
     *
     * @param array $wechatData 微信用户数据
     * @param string $loginType 登录方式
     * @return UsersModel
     */
    public static function createOrUpdateWechatUser($wechatData, $loginType = 'wechat')
    {
        $openidField = $loginType === 'wechat' ? 'wechat_openid' : 'wechat_mp_openid';
        
        $user = self::where($openidField, $wechatData['openid'])->first();
        
        $userData = [
            'nickname' => $wechatData['nickname'] ?? '微信用户',
            'avatar' => $wechatData['avatarUrl'] ?? $wechatData['headimgurl'] ?? null,
            'gender' => isset($wechatData['gender']) ? (int)$wechatData['gender'] : 0,
            $openidField => $wechatData['openid'],
            'login_type' => $loginType,
            'last_login_time' => date('Y-m-d H:i:s'),
        ];
        
        if (isset($wechatData['unionid'])) {
            $userData['wechat_unionid'] = $wechatData['unionid'];
        }
        
        if ($user) {
            $user->update([
                'last_login_time' => date('Y-m-d H:i:s'),
                'last_login_ip' => request()->getRealIp()
            ]);
            return $user;
        } else {
            return self::create($userData);
        }
    }
}